<template>
  <div class="container mx-auto p-6">
    <h1 class="text-2xl font-bold mb-6">发布新房源</h1>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="max-w-3xl"
      @submit.prevent="submitForm"
    >
      <!-- 基础信息 -->
      <el-form-item label="房源标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入房源标题" />
      </el-form-item>

      <el-form-item label="所在城市" prop="city">
        <el-select v-model="form.city" placeholder="请选择城市" class="w-full">
          <el-option
            v-for="city in cities"
            :key="city.value"
            :label="city.label"
            :value="city.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" />
      </el-form-item>

      <el-form-item label="详细描述" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="请输入房源详细描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 租赁信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="租赁类型" prop="rentType">
          <el-radio-group v-model="form.rentType">
            <el-radio label="whole">整租</el-radio>
            <el-radio label="share">合租</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="月租金" prop="monthRent">
          <el-input-number
            v-model="form.monthRent"
            :min="500"
            :max="20000"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>

      <!-- 房屋特征 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="建筑面积" prop="area">
          <el-input-number
            v-model="form.area"
            :min="10"
            :max="500"
            controls-position="right"
            class="w-full"
          >
            <template #append>m²</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="朝向" prop="direction">
          <el-select
            v-model="form.direction"
            placeholder="请选择朝向"
            class="w-full"
          >
            <el-option
              v-for="item in directions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋户型">
          <div class="flex gap-2">
            <el-form-item prop="bedroom" class="m-0">
              <el-input-number
                v-model="form.bedroom"
                :min="0"
                controls-position="right"
                placeholder="室"
              />
            </el-form-item>
            <el-form-item prop="livingRoom" class="m-0">
              <el-input-number
                v-model="form.livingRoom"
                :min="0"
                controls-position="right"
                placeholder="厅"
              />
            </el-form-item>
            <el-form-item prop="kitchen" class="m-0">
              <el-input-number
                v-model="form.kitchen"
                :min="0"
                controls-position="right"
                placeholder="厨"
              />
            </el-form-item>
            <el-form-item prop="toilet" class="m-0">
              <el-input-number
                v-model="form.toilet"
                :min="0"
                controls-position="right"
                placeholder="卫"
              />
            </el-form-item>
          </div>
        </el-form-item>
      </div>

      <!-- 楼层信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="当前楼层" prop="floor">
          <el-input-number
            v-model="form.floor"
            :min="1"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="总楼层" prop="maxFloor">
          <el-input-number
            v-model="form.maxFloor"
            :min="1"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="建成年份" prop="completion_year">
          <el-date-picker
            v-model="form.completion_year"
            type="year"
            value-format="YYYY"
            placeholder="选择年份"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="房产证号" prop="certificate">
          <el-input
            v-model="form.certificate"
            placeholder="请输入房产证编号"
            maxlength="20"
          />
        </el-form-item>
      </div>

      <!-- 设施信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="空调">
          <el-switch
            v-model="form.conditioner"
            active-text="有"
            inactive-text="无"
          />
        </el-form-item>

        <el-form-item label="电梯">
          <el-switch
            v-model="form.elevator"
            active-text="有"
            inactive-text="无"
          />
        </el-form-item>
      </div>

      <!-- 位置信息 -->
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="经度" prop="longitude">
          <el-input-number
            v-model="form.longitude"
            :precision="6"
            :step="0.000001"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input-number
            v-model="form.latitude"
            :precision="6"
            :step="0.000001"
            controls-position="right"
            class="w-full"
          />
        </el-form-item>
      </div>
      <div class="grid grid-cols-2 gap-4">
        <el-form-item label="联系人姓名" prop="contact_name">
          <el-input
            v-model="form.contact_name"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input
            v-model="form.contact_phone"
            placeholder="请输入联系电话"
            maxlength="11"
          />
        </el-form-item>
      </div>

      <!-- 图片上传 -->
      <el-form-item label="房源图片" prop="images">
        <el-upload
          v-model:file-list="form.images"
          action=""
          :auto-upload="false"
          :limit="9"
          list-type="picture-card"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          multiple
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="text-gray-500 text-xs">
              支持JPG/PNG格式，单张不超过5MB，最多9张
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          size="large"
          native-type="submit"
          :loading="submitting"
        >
          立即发布
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import api from "@/api";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
const formRef = ref();
const submitting = ref(false);

const form = reactive({
  title: "",
  city: "北京",
  address: "",
  rentType: "whole",
  monthRent: 2000,
  area: 60,
  bedroom: 1,
  livingRoom: 1,
  kitchen: 1,
  toilet: 1,
  floor: 1,
  maxFloor: 6,
  conditioner: false,
  elevator: false,
  direction: "南",
  contact_name: "",
  contact_phone: "",
  content: "",
  completion_year: new Date().getFullYear(),
  certificate: "",
  longitude: 116.4074,
  latitude: 39.9042,
  images: [],
});

const rules = {
  title: [
    { required: true, message: "请输入房源标题", trigger: "blur" },
    { min: 5, max: 50, message: "长度在5到50个字符", trigger: "blur" },
  ],
  city: { required: true, message: "请选择所在城市", trigger: "change" },
  address: { required: true, message: "请输入详细地址", trigger: "blur" },
  monthRent: { required: true, message: "请输入月租金", trigger: "blur" },
  area: { required: true, message: "请输入建筑面积", trigger: "blur" },
  floor: { required: true, message: "请输入当前楼层", trigger: "blur" },
  maxFloor: { required: true, message: "请输入总楼层数", trigger: "blur" },
  longitude: [
    { required: true, message: "请输入经度", trigger: "blur" },
    {
      validator: (_, v) => v >= -180 && v <= 180,
      message: "经度范围：-180 ~ 180",
      trigger: "blur",
    },
  ],
  latitude: [
    { required: true, message: "请输入纬度", trigger: "blur" },
    {
      validator: (_, v) => v >= -90 && v <= 90,
      message: "纬度范围：-90 ~ 90",
      trigger: "blur",
    },
  ],
  direction: { required: true, message: "请选择房屋朝向", trigger: "change" },
  contact_name: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度2-10个字符", trigger: "blur" },
  ],
  contact_phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
  content: [
    { required: true, message: "请输入房源描述", trigger: "blur" },
    { min: 20, max: 500, message: "描述需20-500个字符", trigger: "blur" },
  ],
  completion_year: [
    { required: true, message: "请选择建成年份", trigger: "change" },
    {
      validator: (_, v) => {
        const currentYear = new Date().getFullYear();
        return Number(v) <= currentYear;
      },
      message: "年份不能超过当前年份",
      trigger: "change",
    },
    {
      validator: (_, v) => v >= 1900,
      message: "年份不能早于1900年",
      trigger: "change",
    },
  ],
  images: [
    {
      validator: (_, v, cb) => {
        if (v.length < 1) return cb(new Error("至少上传1张图片"));
        if (v.length > 9) return cb(new Error("最多上传9张图片"));
        cb();
      },
      trigger: "change",
    },
  ],
};

const cities = [
  { label: "北京市", value: "北京" },
  { label: "上海市", value: "上海" },
  { label: "广州市", value: "广州" },
  { label: "深圳市", value: "深圳" },
];

const directions = [
  { label: "东", value: "东" },
  { label: "南", value: "南" },
  { label: "西", value: "西" },
  { label: "北", value: "北" },
  { label: "东南", value: "东南" },
  { label: "东北", value: "东北" },
  { label: "西南", value: "西南" },
  { label: "西北", value: "西北" },
];

const handleFileChange = (uploadFile) => {
  if (uploadFile.status === "fail") {
    ElMessage.error(`${uploadFile.name} 上传失败`);
    form.images = form.images.filter((f) => f.uid !== uploadFile.uid);
  }
};
const disableFutureYears = (date) => {
  return date.getFullYear() > new Date().getFullYear();
};

const beforeUpload = (file) => {
  const validTypes = ["image/jpeg", "image/png"];
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!validTypes.includes(file.type)) {
    ElMessage.error("仅支持JPG/PNG格式");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB");
    return false;
  }
  return true;
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;
    const currentUserId = userStore.userInfo.id;
    const formData = new FormData();
    const houseData = {
      ...form,
      completionYear: Number(form.completion_year),
      contactName: form.contact_name,
      contactPhone: form.contact_phone,
      images: undefined,
      conditioner: form.conditioner ? 1 : 0,
      elevator: form.elevator ? 1 : 0,
    };

    formData.append(
      "house",
      new Blob([JSON.stringify(houseData)], { type: "application/json" })
    );

    form.images.forEach((file) => {
      formData.append("images", file.raw);
    });

    const res = await api.house.addHouse(currentUserId, formData);

    if (res.code === 200) {
      ElMessage.success("房源提交成功，等待审核");
      formRef.value.resetFields();
    } else {
      ElMessage.error(res.message || "提交失败");
    }
  } catch (error) {
    console.error("提交错误:", error);
    ElMessage.error(error.response?.data?.message || error.message);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.container {
  background-color: #f8fafc;
  min-height: 100vh;
}
.el-form-item__label {
  @apply font-semibold text-gray-700;
}
</style>
